package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {


    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;


    @Override
    public PageResult getItemList(PageResult pageResult) {

        //1.总数
        //2.分页结果
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper<Item> queryWrapper =new QueryWrapper<>();
        queryWrapper.like(flag,"name",pageResult.getQuery());

        //编辑mp的分页对象 四个属性有用(页数/条数/总数/记录) 传递= 页面/条数
        IPage<Item> page = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
         page = itemMapper.selectPage(page, queryWrapper);
         //获取总数
        long total = page.getTotal();
        //获取记录数
        List<Item> rows = page.getRecords();
        //将数据封装
        return pageResult.setTotal(total).setRows(rows);
    }
    @Transactional
    @Override
    public void saveItem(ItemVO itemVO) {

        Item item = itemVO.getItem();
        System.out.println(item);
        item.setStatus(true);

        //要求：item入库之后，动态返回Id
        //mp原则：入库之后动态回显数据
        itemMapper.insert(item);
        //实现itemDesc对象入库
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);

    }
    @Transactional
    @Override
    public void deleteItemById(Integer id) {
        itemMapper.deleteById(id);
    }

    @Transactional
    @Override
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }

    @Transactional
    @Override
    public void updateItem(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    public Item findallById(Integer id) {
        return itemMapper.selectById(id);

    }


}
